
use tokio::sync::mpsc;
use tokio::time;

#[tokio::main]
async fn main() {


    let mut db = vec![1,2,3];
    let (tx, mut rx) = mpsc::channel::<i32>(20);

    // tx本质上是arc
    let tx1 = tx.clone();
    let tx2 = tx.clone();

    // 代码遇到tokio::spawn会自动创建一个task并执行，只是不阻塞当前线程
    let process_task = tokio::spawn(async move {
        while let Some(value) = rx.recv().await {
            println!("got = {}", value);
            db[1] = value;
            println!("db = {:?}", db);
        }
    });

    let task1 = tokio::task::spawn(async move {
        println!("task1 run");
        if let Err(_) = tx1.send(1).await {
            time::sleep(time::Duration::from_secs(2)).await;
        }

    });

    let task2 = tokio::task::spawn(async move {
        println!("task2 run");
        if let Err(_) = tx2.send(2).await {
            time::sleep(time::Duration::from_secs(2)).await;
        }

    });

    time::sleep(time::Duration::from_secs(3)).await;

    println!("main run1");
    // 遇到.await会阻塞当前线程，等待task执行完毕，然后继续执行
    task1.await.unwrap();
    println!("main run2");
    task2.await.unwrap();
    println!("main run3");
    process_task.await.unwrap();
}